'''
@author: Michael Cotterell
'''

import os
from django.utils import simplejson
from google.appengine.api import urlfetch

'''
An object for querying TMDb using its RESTful API
@author: Michael Cotterell
'''
class TMDb(object):
    
    endpoint = 'http://api.themoviedb.org/2.1'
    language = 'en'
    format = 'json'
    
    methods = {'search':'Movie.search', 
               'imdbLookup':'Movie.imdbLookup', 
               'getInfo':'Movie.getInfo', 
               'getImages':'Movie.getImages', 
               'getVersion':'Movie.getVersion'}
    
    def __init__(self, apikey):
        self.apikey = apikey
    
    def apiurl(self, method):
        return self.endpoint + '/' + self.methods[method] + '/' + self.language + '/' + self.format + '/' + self.apikey + '/'
    
    def search(self, title):
        url = self.apiurl('search') + title
        result = urlfetch.fetch(url)
        json = simplejson.loads(result.content)
        return json
    
    def imdbLookup(self, imdbid):
        url = self.apiurl('imdbLookup') + imdbid
        result = urlfetch.fetch(url)
        json = simplejson.loads(result.content)
        return json
    
    def getInfo(self, tmdbid):
        url = self.apiurl('getInfo') + tmdbid
        result = urlfetch.fetch(url)
        json = simplejson.loads(result.content)
        return json
    
    def getImages(self, id):
        url = self.apiurl('getImages') + id
        result = urlfetch.fetch(url)
        json = simplejson.loads(result.content)
        return json
    
    def getVersion(self, tmdbid):
        url = self.apiurl('getVersion') + tmdbid
        result = urlfetch.fetch(url)
        json = simplejson.loads(result.content)
        return json
    